package com.Register.task;

import com.Register.service.SkillDocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class BrowserCountScheduler {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SkillDocumentService skillDocumentService;

    // 该方法每天 24:00 执行
    @Scheduled(cron = "0 0 0 * * ?")  // cron 表达式: 每天 0 点执行
    public void persistBrowserCounts() {
        // 获取所有需要持久化的 skillDocumentId
        List<Long> skillDocumentIds = skillDocumentService.getAllSkillDocumentIds();

        for (Long skillDocumentId : skillDocumentIds) {
            String redisKey = "DocumentViews" + skillDocumentId;
            String viewCountStr = stringRedisTemplate.opsForValue().get(redisKey);

            if (viewCountStr != null) {
                Long viewCount = Long.valueOf(viewCountStr);

                // 将浏览数持久化到数据库
                skillDocumentService.updateSkillDocumentViewCount(skillDocumentId, viewCount);
            }
        }
    }
}
